package com.surveypark.util;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.surveypark.service.RightService;

public class GenerateAllRightsUtil {

	private static ApplicationContext context;
	private static RightService rs;

	public static void main(String[] args) throws Exception {

		context = new ClassPathXmlApplicationContext(
				"spring/applicationContext.xml");
		rs = (RightService) context.getBean("rightService");

		URL url = ClassLoader
				.getSystemResource("com/surveypark/struts2/action");
		File dir = new File(url.toURI());
		File[] files = dir.listFiles();
		String fname = "";
		for (File file : files) {
			fname = file.getName();
			if (fname.endsWith("class") && !"BaseAction.class".equals(fname)
					&& !"UserAware.class".equals(fname)) {
				processClass(fname);
			}
		}
	}

	@SuppressWarnings("rawtypes")
	private static void processClass(String fname) throws Exception {

		String pkgName = "com.surveypark.struts2.action";
		String simpleClassName = fname.substring(0, fname.indexOf("."));
		Class clazz = Class.forName(pkgName + "." + simpleClassName);
		Method[] methods = clazz.getDeclaredMethods();

		String mname = "";
		Class retType = null;
		Class[] paramType = null;

		String url = "";
		for (Method m : methods) {
			mname = m.getName();
			retType = m.getReturnType();
			paramType = m.getParameterTypes();

			if ((retType == String.class) && !ValidateUtil.isValid(paramType)
					&& Modifier.isPublic(m.getModifiers())) {
				url = "/" + simpleClassName + "_" + mname;
				if(mname.equals("execute")){
					url = "/" + simpleClassName;
				}else{
					url = "/" + simpleClassName + "_" + mname;
				}
				rs.appendRightByURL(url);
			}
		}
	}
}
